package com.solution.service;

import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.apache.log4j.Logger;

import com.solution.constant.CommunicationConstants;
import com.solution.constant.StatusConstants;
import com.solution.dao.CommunicationDAO;
import com.solution.dao.DAOFactory;
import com.solution.model.Communication;
import com.solution.util.EmailSender;
import com.solution.util.SMSSender;

@MessageDriven(name="CommunicationMessageBean", activationConfig = {
		@ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"),
	    @ActivationConfigProperty(propertyName="destination", propertyValue="queue/communication/MessageQueue")
	})
public class CommunicationMessageBean implements MessageListener{

	@Resource
    private MessageDrivenContext context;
	
	/**
	 * DAO instance.
	 */
	private CommunicationDAO communicationDao = (CommunicationDAO)DAOFactory.getDAOInstance(CommunicationDAO.class.getName());
	
	/**
	 * Logger instance.
	 */
	private Logger log = Logger.getLogger(CommunicationServiceImpl.class.getName());
	
	public void onMessage(Message message) {
        boolean successFlag = false;
        try{
            if (message instanceof ObjectMessage) {
                ObjectMessage objMessage = (ObjectMessage) message;
                Object obj = objMessage.getObject();
                if (obj instanceof Communication){
                	Communication communication = (Communication)obj;
                	// for single sending.
                	if(communication.getCommunicationType().getName().equalsIgnoreCase(CommunicationConstants.COMMUNICATION_TYPE_SMS)){
                		//send SMS.
                		successFlag = SMSSender.sendStaticContentSMS(communication);
                	}
                	else if(communication.getCommunicationType().getName().equalsIgnoreCase(CommunicationConstants.COMMUNICATION_TYPE_EMAIL)){
                		//send Email.
                		successFlag = EmailSender.dispatchStaticContentEmail(communication);
                	}
                	else if(successFlag){
                		// close the entry in the communication log.
                		communication.setStatus(new Short(StatusConstants.CLOSE));
                		communicationDao.createOrUpdate(communication);
                	}
                }
                else{
                    log.error("Expecting Communication Object in Message");
                }
            } 
            else {
            	log.error("Expecting Object Message");
            }
        } 
        catch (Throwable t) {
            t.printStackTrace();
            context.setRollbackOnly();
        }
    }
}
